package com.wuzihao.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuzihao.reggie.common.CustomException;
import com.wuzihao.reggie.entity.Category;
import com.wuzihao.reggie.entity.Dish;
import com.wuzihao.reggie.entity.Setmeal;
import com.wuzihao.reggie.mapper.CategoryMapper;
import com.wuzihao.reggie.service.CategoryService;
import com.wuzihao.reggie.service.DishService;
import com.wuzihao.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    CategoryService categoryService;

    @Autowired
    DishService dishService;

    @Autowired
    SetmealService setmealService;

    @Override
    public Page pageInfo(int page, int pageSize) {
        Page pageInfo = new Page(page,pageSize);
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("sort");

        categoryService.page(pageInfo,queryWrapper);
        return pageInfo;
    }

    @Override
    public void delete(Long id) {
        //1.判断当前分类是否关联菜品分类
        int dishCount = dishService.count(new QueryWrapper<Dish>().eq("category_id", id));
        if(dishCount > 0){
            //抛出异常
            throw new CustomException("当前分类下已经关联菜品，不能删除");
        }
        //2.判断当前分类是否关联套餐分类
        int setmealCount = setmealService.count(new QueryWrapper<Setmeal>().eq("category_id", id));
        if(setmealCount > 0){
            //抛出异常
            throw new CustomException("当前分类下已经关联套餐，不能删除");
        }
        //3.成功删除
        categoryService.removeById(id);
    }

    @Override
    public List<Category> listCategory(Category category) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(category.getType()!=null,"type",category.getType());
        queryWrapper.orderByAsc("sort").orderByDesc("update_time");

        List<Category> list = categoryService.list(queryWrapper);
        return list;
    }
}
